<script setup lang="ts">
import type { FormInstance } from 'ant-design-vue';

import type { Dept, User } from '#/api';

import { computed, reactive, ref, watch } from 'vue';

import {
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Modal,
  Radio,
  RadioGroup,
  Select,
  SelectOption,
  TreeSelect,
} from 'ant-design-vue';

import {
  addDeptApi,
  getParentDeptOptionsApi,
  getUserListApi,
  updateDeptApi,
} from '#/api';
import { prepareCreateData, prepareUpdateData } from '#/utils/form';

interface Props {
  visible: boolean;
  deptData?: Dept;
  parentDept?: Dept; // 新增子部门时的父部门
}

const props = defineProps<Props>();
const emit = defineEmits(['update:visible', 'success']);

const formRef = ref<FormInstance>();
const confirmLoading = ref(false);

// 父部门选项
const parentDeptOptions = ref<Dept[]>([]);
// 用户选项（部门领导）
const userOptions = ref<User[]>([]);
const userLoading = ref(false);

// 是否编辑模式
const isEdit = computed(() => !!props.deptData?.id);

// 表单数据
const formData = reactive<Dept>({
  id: undefined,
  parentId: 0,
  deptName: '',
  deptCode: '',
  leader: undefined,
  phone: '',
  email: '',
  sort: 0,
  status: 1,
});

// 表单验证规则
const rules = {
  deptName: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
  deptCode: [{ required: true, message: '请输入部门编码', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  email: [
    {
      type: 'email',
      message: '请输入正确的邮箱格式',
      trigger: 'blur',
    },
  ],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号格式',
      trigger: 'blur',
    },
  ],
};

// 监听部门数据变化
watch(
  () => props.deptData,
  (newVal) => {
    if (newVal) {
      Object.assign(formData, newVal);
    } else {
      resetForm();
    }
  },
  { immediate: true },
);

// 监听父部门变化（新增子部门时）
watch(
  () => props.parentDept,
  (newVal) => {
    if (newVal && !props.deptData) {
      formData.parentId = newVal.id;
    }
  },
  { immediate: true },
);

// 监听弹窗显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      fetchParentDeptOptions();
      fetchUserOptions();
    }
  },
);

// 重置表单
function resetForm() {
  formData.id = undefined;
  formData.parentId = 0;
  formData.deptName = '';
  formData.deptCode = '';
  formData.leader = undefined;
  formData.phone = '';
  formData.email = '';
  formData.sort = 0;
  formData.status = 1;
  formRef.value?.clearValidate();
}

// 获取父部门选项
async function fetchParentDeptOptions() {
  try {
    const data = await getParentDeptOptionsApi();
    parentDeptOptions.value = data || [];
  } catch (error: any) {
    message.error(error?.msg || '获取父部门选项失败');
  }
}

// 获取用户选项（部门领导）
async function fetchUserOptions() {
  userLoading.value = true;
  try {
    const data = await getUserListApi({
      pageNum: 1,
      pageSize: 1000, // 获取所有用户
      status: 1, // 只获取启用的用户
    });

    // 处理分页数据
    if (Array.isArray(data)) {
      userOptions.value = data;
    } else {
      userOptions.value = data.list || data.records || [];
    }
  } catch (error: any) {
    message.error(error?.msg || '获取用户列表失败');
  } finally {
    userLoading.value = false;
  }
}

// 转换部门树数据为TreeSelect需要的格式
function convertToTreeData(depts: Dept[]): any[] {
  return depts.map((dept) => ({
    value: dept.id,
    title: dept.deptName,
    key: dept.id,
    children: dept.children ? convertToTreeData(dept.children) : undefined,
  }));
}

// 确定
async function handleOk() {
  try {
    await formRef.value?.validate();
    confirmLoading.value = true;

    if (isEdit.value) {
      // 编辑：移除审计字段
      await updateDeptApi(prepareUpdateData(formData) as Dept);
      message.success('编辑成功');
    } else {
      // 新增：移除审计字段和 id
      await addDeptApi(prepareCreateData(formData) as Dept);
      message.success('新增成功');
    }

    emit('success');
    handleCancel();
  } catch (error) {
    console.error('保存部门失败:', error);
  } finally {
    confirmLoading.value = false;
  }
}

// 取消
function handleCancel() {
  emit('update:visible', false);
  resetForm();
}
</script>

<template>
  <Modal
    :visible="visible"
    :title="isEdit ? '编辑部门' : '新增部门'"
    :confirm-loading="confirmLoading"
    width="600px"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <Form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <FormItem label="父部门" name="parentId">
        <TreeSelect
          v-model:value="formData.parentId"
          :tree-data="[
            { value: 0, title: '顶级部门', key: 0 },
            ...convertToTreeData(parentDeptOptions),
          ]"
          placeholder="请选择父部门"
          :tree-default-expand-all="true"
          allow-clear
        />
      </FormItem>

      <FormItem label="部门名称" name="deptName">
        <Input
          v-model:value="formData.deptName"
          placeholder="请输入部门名称"
          allow-clear
        />
      </FormItem>

      <FormItem label="部门编码" name="deptCode">
        <Input
          v-model:value="formData.deptCode"
          placeholder="请输入部门编码"
          allow-clear
        />
      </FormItem>

      <FormItem label="部门领导" name="leader">
        <Select
          v-model:value="formData.leader"
          placeholder="请选择部门领导"
          :loading="userLoading"
          show-search
          :filter-option="
            (input: string, option: any) => {
              const user = userOptions.find((u) => u.id === option.value);
              if (!user) return false;
              return (
                user.username?.toLowerCase().includes(input.toLowerCase()) ||
                user.nickname?.toLowerCase().includes(input.toLowerCase())
              );
            }
          "
          allow-clear
        >
          <SelectOption
            v-for="user in userOptions"
            :key="user.id"
            :value="user.id"
          >
            {{ user.nickname || user.username }} ({{ user.username }})
          </SelectOption>
        </Select>
      </FormItem>

      <FormItem label="联系电话" name="phone">
        <Input
          v-model:value="formData.phone"
          placeholder="请输入联系电话"
          allow-clear
        />
      </FormItem>

      <FormItem label="邮箱" name="email">
        <Input
          v-model:value="formData.email"
          placeholder="请输入邮箱"
          allow-clear
        />
      </FormItem>

      <FormItem label="排序" name="sort">
        <InputNumber
          v-model:value="formData.sort"
          :min="0"
          placeholder="请输入排序号"
          style="width: 100%"
        />
      </FormItem>

      <FormItem label="状态" name="status">
        <RadioGroup v-model:value="formData.status">
          <Radio :value="1">正常</Radio>
          <Radio :value="0">停用</Radio>
        </RadioGroup>
      </FormItem>
    </Form>
  </Modal>
</template>

<style scoped>
:deep(.ant-form-item) {
  margin-bottom: 16px;
}
</style>

